package top.jacktgq.file

import groovy.json.JsonOutput
import groovy.json.JsonSlurper
import top.jacktgq.oop.Person

/**
 @Author CandyWall
 @Date 2021/4/28--0:24
 @Description 对象和json字符串的互相转换
 */
def list = [
        new Person(name: '空条承太郎', age: 17),
        new Person(name: '花京院典明', age: 18),
        new Person(name: '乔瑟夫乔斯达', age: 69),
        new Person(name: '阿布德尔', age: 40),
        new Person(name: '波鲁那雷夫', age: 38),
        new Person(name: '伊奇', age: 12)
]
def jsonstr = JsonOutput.toJson(list)
println jsonstr
println JsonOutput.prettyPrint(jsonstr)

// 将Json字符串转成groovy对象
def jsonSlurper = new JsonSlurper()
println jsonSlurper.parse(jsonstr.getBytes())

// 模拟从网络上请求JSON字符串，然后将JSON字符串转成相应的groovy对象
def getNetworkData(String url) {
    // 发送HTTP请求
    def conn = new URL(url).openConnection()
    conn.setRequestMethod('POST')
    conn.connect()
    def response = conn.content.text
    // 将json转换成groovy对象
    def jsonSlurper = new JsonSlurper()
    return jsonSlurper.parse(response.getBytes())
}

println getNetworkData('http://localhost:8080/user/admin/query_userinfo')